package frame.system.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import frame.base.BaseConstant;
import frame.base.BaseService;
import frame.base.BootstrapTable;
import frame.system.mapper.PermissionMapper;
import frame.system.mapper.RoleMapper;
import frame.system.qo.AuthQo;
import frame.system.to.Role;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.common.Mapper;

import java.util.List;


/**
 * Role 模块服务类
 * <br>
 * @author PeiWentao
 * @since 2020-05-20 14:08
 */
@Service
public class RoleService extends BaseService<Integer, Role, AuthQo> {

	@Autowired
    private RoleMapper roleMapper;

    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    protected Mapper<Role> mainMapper() {
        return roleMapper;
    }

    @Override
	public BootstrapTable<Role> pageList(final AuthQo qo) {
        //分页查询
        Page<Role> page = PageHelper.startPage(qo.page(), qo.size()).doSelectPage(() -> {
            roleMapper.pageList(qo);
        });
        return new BootstrapTable<Role>(page.getTotal(),page.getResult());
	}


	public List<Role> allList() {
        final AuthQo qo = new AuthQo();
        qo.setValid(BaseConstant.TO_VALID);
        qo.setOrderStr("id asc");
        return roleMapper.pageList(qo);
    }

    /**
     * 给角色添加权限
     * @param rId 角色id
     * @param permissionIds 权限ids
     * @return
     */
    @Transactional
    public int addPermission(Integer rId, List<Integer> permissionIds) {
        int result = 0;
        result += roleMapper.deletePermissions(rId);
        if (permissionIds != null && permissionIds.size() > 0) {
            result += roleMapper.addPermissions(rId, permissionIds);
        }
        return result;
    }

    @Override
    protected void preAdd(Role record) {
        super.preAdd(record);
        record.setId(null);
    }

    @Override
    protected Role newInstanceT(Integer id) {
        return new Role(id);
    }
}
